package com.cn.hospital.service.impl.auth;

import cn.dev33.satoken.stp.StpUtil;
import com.cn.hospital.message.Msg;
import com.cn.hospital.service.auth.LogoutService;
import com.cn.hospital.utils.AppJwtUtil;
import com.cn.hospital.utils.RedisUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;

@Service
@Log4j2
public class LogoutServiceImpl implements LogoutService {

    private String jwtRedisTokenValue = null;
    private String redisSaTokenValue = null;
    private String stpSaTokenValue = null;

    @Autowired
    RedisUtils redisUtils;

    @Override
    public Msg logout(Map<String, Object> stpMap) {
        if (isTokenNotNull(String.valueOf(stpMap.get("stpSaTokenValue")))) {
            Claims claims = AppJwtUtil.getClaimsBody(jwtRedisTokenValue);
            int isTokenScope = AppJwtUtil.verifyToken(claims);
            if (isTokenScope == -1 || isTokenScope == 0) {
                Object userId = claims.get("id");
                Object loginId = stpMap.get("loginId");
                if (isIdEquals(userId, loginId)) {
                    redisUtils.remove("token");
                    redisUtils.remove("sa-token");
                    log.info("stpSaTokenValue : {}", stpSaTokenValue);
                    log.info("redisSaTokenValue : {}", redisSaTokenValue);
                    log.info("token已清除,下线成功 userId:{}", userId);
                }
            } else {
                return Msg.okResult(404, "登录信息有误");
            }
        } else {
            return Msg.okResult(404, "请先登录在操作!");
        }
        return Msg.okResult(200, "下线成功");
    }

    /**
     * 判断信息是否有误
     *
     * @param stpSaTokenValue
     * @return
     */
    public Boolean isTokenNotNull(String stpSaTokenValue) {
        this.jwtRedisTokenValue = String.valueOf(redisUtils.get("token"));
        this.redisSaTokenValue = String.valueOf(redisUtils.get("sa-token"));
        this.stpSaTokenValue = stpSaTokenValue;

        if (StringUtils.isEmpty(jwtRedisTokenValue) || StringUtils.isEmpty(redisSaTokenValue) || StringUtils.isEmpty(this.stpSaTokenValue)) {
            return false;
        }
        if (redisSaTokenValue.equals(this.stpSaTokenValue)) {
            return true;
        }
        return false;
    }

    private boolean isIdEquals(Object userId, Object loginId) {
        if ((userId + "").equals(loginId + "")) {
            return true;
        }
        return false;
    }
}
